package org.mysfit.ctp4j.api.controller.v1;

import org.mysfit.ctp4j.core.MyCThostFtdcMdSpi;
import org.mysfit.ctp4j.core.service.CommonService;
import org.mysfit.ctp4j.core.service.MarketService;
import org.mysfit.ctp4j.infra.pojo.ApiResponse;
import org.mysfit.ctp4j.infra.pojo.CtpConfig;
import org.mysfit.ctp4j.infra.pojo.CtpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import ctp.thosttraderapi.CThostFtdcMdApi;

/**
 * 
 * @author long.gf
 *
 */
@RestController
@RequestMapping("/v1/market")
public class MarketController {
	
	@Autowired
	private CommonService commonService;
	@Autowired
	private MarketService marketService;
	
	private void initMarket(CtpConfig ctpConfig, CtpUser ctpUser) {
		CThostFtdcMdApi mdApi = CThostFtdcMdApi.CreateFtdcMdApi();
		MyCThostFtdcMdSpi mdSpi = new MyCThostFtdcMdSpi(ctpUser, mdApi, marketService);
		mdApi.RegisterSpi(mdSpi);
		// 只在交易时段调用
		mdApi.RegisterFront(ctpConfig.getMarketFront1());
		mdApi.Init();
		mdApi.Join();
	}
	
	@GetMapping("/subscribe/{investorId}")
	public ApiResponse<String> subscribe(@PathVariable("investorId")String investorId) {
		CtpConfig ctpConfig = commonService.getConfig();
		CtpUser ctpUser = commonService.getUser(investorId);
		new CtpUser(ctpUser);
		new Thread(() -> {
			this.initMarket(ctpConfig, ctpUser);
		}).start();
		return ApiResponse.ok();
	}
}
